package controller

import (
	"encoding/json"
	"git.900sui.cn/kc/base/common/functions"
	"git.900sui.cn/kc/kcgin/logs"
	"git.900sui.cn/kc/rpcinterface/client/pay"
	pay2 "git.900sui.cn/kc/rpcinterface/interface/pay"
	"strings"
)

//银联授权回调地址信息
type YinlianController struct {
	functions.Controller
}

//获取UserAgent 支付标识信息 格式 UnionPay/1.0APP自定义信息
func (y *YinlianController) GetUserAgentWithPayCode(search_str string) string {
	UniionPayindex := strings.Index(search_str, "UnionPay/1.0")
	newStr := search_str[UniionPayindex:]
	KIndex := strings.Index(newStr, ")")
	PayCode := newStr[0:KIndex]
	return PayCode
}

const UserAgentField = "User-Agent"

func (y *YinlianController) Index() {
	choseType := y.Input.Get("choseType").String()
	orderSn := y.Input.Get("orderSn").String()
	userAuthcode := y.Input.Get("userAuthCode").String()
	resp := y.Input.Get("respCode").String()
	cid := y.Input.Get("cid").String()
	//userAgent := "UnionPay/1.0 CloudPay"
	userAgentOrign := y.Input.Header(UserAgentField).String()
	userAgent := y.GetUserAgentWithPayCode(userAgentOrign)

	logs.Info("choseType: %s,orderSn: %s, userCode: %s, rep:%s, userGent: %s", choseType, orderSn, userAuthcode, resp, userAgent)
	client := new(pay.XindaluPay).Init()
	context := y.Ctx.Request.Context()
	args := &pay2.ArgsGetPaypalTag{
		Ip:       functions.ClientIP(y.Ctx.Request),
		PayCode:  userAgent,
		AuthCode: userAuthcode,
		Cid:      "383",
	}
	reply := &pay2.ReplyGetPaypalTag{}
	err := client.GetPaypalTag(context, args, reply)
	if err != nil {
		y.Output.Error("40001", err.Error())
	}

	logs.Info("reply: %+v", reply.Data)

	unionOrderYinlianArgs := &pay2.ArgsunionidOrder{
		OrderNO:   orderSn,
		PayWay:    pay2.PayWayYinlian,
		Openid:    reply.Data.UserId, //返回的用户的标识信息
		AtqTag:    reply.Data.AtqTag,
		Ip:        functions.ClientIP(y.Ctx.Request),
		CustLogin: "13255999580", //商户手机号
		Cid:       cid,
	}
	unionOrderReply := &pay2.ReplyUniondOrder{}

	err = client.UnionidOrder(context, unionOrderYinlianArgs, unionOrderReply)
	if err != nil {
		y.Output.Error("4000", err.Error())
	}
	//y.Output.Success(unionOrderReply.Data)
	logs.Info("%#v", unionOrderReply.Data)
	content, _ := json.Marshal(unionOrderReply.Data)
	data := make(map[string]string)
	json.Unmarshal(content, &data)
	y.Ctx.Redirect(301, data["redirecturl"])
}

//银联callback回调信息
func (y *YinlianController) Callback() {
	userAuthcode := y.Input.Get("userAuthCode").String()
	userAgentOrign := y.Input.Header(UserAgentField).String()
	userAgent := y.GetUserAgentWithPayCode(userAgentOrign)
	reply := make(map[string]string)
	reply["userAuthcode"] = userAuthcode
	reply["payCode"] = userAgent
	logs.Info("code :%s, pay: %s", userAuthcode, userAgent)
	y.Output.Success(reply)
}
